package com.globalresources.business.impl;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.globalresources.business.inface.IFileOperatorService;
import com.globalresources.commons.Constant;
import com.globalresources.commons.FileOperate;
import com.globalresources.commons.PDFOperate;
import com.globalresources.commons.PublicUtil;
import com.globalresources.commons.vo.FileWrapper;
import com.globalresources.dao.inface.ICityDao;
import com.globalresources.dao.inface.IHospitalDao;
import com.globalresources.po.City;
import com.globalresources.po.Hospital;

/**
 * @author aaron.lu(luzhiyuan) E-mail:atyuan.lu@gmail.com
 * @since 创建时间：Jul 26, 2009 9:31:23 AM
 */
public class FileOperatorServiceImpl implements IFileOperatorService{
	
	Logger logger = Logger.getLogger(this.getClass());
	private String hospitalPath;
	private String userPath;
	private String backPath;
	private ICityDao cityDao;
	private IHospitalDao hospitalDao;
	
	
	public IHospitalDao getHospitalDao() {
		return hospitalDao;
	}
	public void setHospitalDao(IHospitalDao hospitalDao) {
		this.hospitalDao = hospitalDao;
	}
	public ICityDao getCityDao() {
		return cityDao;
	}
	public void setCityDao(ICityDao cityDao) {
		this.cityDao = cityDao;
	}
	public String getHospitalPath() {
		return hospitalPath;
	}
	public void setHospitalPath(String hospitalPath) {
		this.hospitalPath = hospitalPath;
	}


	public Logger getLogger() {
		return logger;
	}
	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	
	
	/**
	 * <P>剪切文件到指定文件下
	*@author aaron.lu(luzhiyuan)
	*@param absoultFilePath
	*@param userId
	*@param documentName
	*@return
	*@throws IOException
	 */
	public boolean moveFile(String absoultFilePath, Integer userId, String documentName) throws IOException{
		boolean result = false;
		File pdf_file = new File(absoultFilePath);
		if (pdf_file.exists()) {
			File dir = new File(getUserPath() + "/" +userId);
			if (!dir.exists()) {
				FileOperate.createFolder(getUserPath() + "/" +userId);
				dir = new File(getUserPath() + "/" +userId);
				FileOperate.createFile(dir.getAbsolutePath() + "/" + documentName);
			}
			FileOperate.moveFile(pdf_file.getAbsolutePath(), dir.getAbsolutePath() + "/" + documentName);
			result = true;
		}
		
		return result;
	}
	
	/**
	 * <p>分隔文件
	*@author aaron.lu(luzhiyuan)
	*@param path
	*@param tofrom
	*@param toend
	*@return
	 */
	public boolean splitFile(String path, int tofrom, int toend){
		boolean result = false;
		File pdf_file = new File(path);
		if (pdf_file.exists()) {
			try {
				PDFOperate.partitionPdfFile(path, tofrom, toend);
				result = true;
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		return result;
	}
	
	/**
	 * 备份文件
	*@author aaron.lu(luzhiyuan)
	*@param path
	*@return
	 */
	public boolean backupFile(String path){
		boolean result = true;
		String filename = path.substring(path.lastIndexOf("\\") + 1, path.length());
		File file = new File(getBackPath() + "/" + filename);
		String backuppath = getBackPath() + "/" + filename;
		if(file.exists()){
			backuppath = getBackPath() + "/" + filename + new Date().getTime();
		}
		try {
			FileOperate.moveFile(path, backuppath);
		} catch (IOException e) {
			result = false;
			logger.error(e.getMessage());
		}
		return result;
	}
	
	/**
	 * <p>查询城市列表
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public List<City> getCities(){
		return cityDao.findAll();
	}
	
	/**
	 * <p>查询医院列表
	*@author aaron.lu(luzhiyuan)
	*@return
	 */
	public List<Hospital> getHospitals(){
		return hospitalDao.findAll();
	}
	
	/**
	 * <p>遍历文件夹，读所有文档信息
	*@author aaron.lu(luzhiyuan)
	*@return List
	*@throws ParseException
	 */
	public List<FileWrapper> getAllFilesUnProcess() throws ParseException{
		File[] _hospital_floders =  FileOperate.readFolderByFile(hospitalPath);
		List<FileWrapper> result = new ArrayList<FileWrapper>();
		for (int i = 0; i < _hospital_floders.length; i++) {
			FileWrapper fileWrapper = wrapFile(_hospital_floders[i]);
			if (null != fileWrapper) {
				result.add(fileWrapper);
			}
		}	
		return result;
	}
	
	/**
	 * <p>获得文件夹下所有文档
	*@author aaron.lu(luzhiyuan)
	*@param folder
	*@return
	*@throws ParseException
	 */
	public List<FileWrapper> getAllFilesUnderFloder(String folder) throws ParseException{
		String folderPath = getHospitalPath() + "//" + folder;
		File[] _hospital_files =  FileOperate.readFolderByFile(folderPath);
		List<FileWrapper> result = new ArrayList<FileWrapper>();
		for (int i = 0; i < _hospital_files.length; i++) {
			FileWrapper fileWrapper	= wrapFile(_hospital_files[i]);
			if (null != fileWrapper) {
				result.add(fileWrapper);
			}
		}
		return result;
	}
	
	/**
	 * <p>封装File实体为FileWrapper
	*@author aaron.lu(luzhiyuan)
	*@param file File
	*@return FileWrapper
	*@throws ParseException
	 */	
	private FileWrapper wrapFile(File file) throws ParseException{
		if (null != file) {
			File[] _files = file.listFiles();
			int newFileAmountForTaday = 0;
			int allFileAmount = 0;
			if (null !=_files && _files.length >0) {
				for (int i = 0; i < _files.length; i++) {
					if (_files[i].isFile()) {
						if (isPDF(_files[i])) {
							allFileAmount ++;
							if (PublicUtil.isToday(new Date(_files[i].lastModified()))) {
								newFileAmountForTaday ++;
							}
						}					
					}
				}
			}		
			FileWrapper fileWrapper = new FileWrapper(file.getName(), new Date(file.lastModified()), file.isDirectory(), file.isFile(), file.getAbsolutePath(), file.getParent(), newFileAmountForTaday, allFileAmount);
			fileWrapper.setDistance(PublicUtil.getDistance(fileWrapper.getLastModified()));
			return fileWrapper;
		}
		return null;
	}
	
	/**
	 * <p>判断是否为pdf文件
	*@author aaron.lu(luzhiyuan)
	*@param file File
	*@return boolean
	 */
	private boolean isPDF(File file){
		boolean reslut = false;
		if (file.getAbsolutePath().endsWith(Constant.POSTFIX_PDF_LOWCASE) || file.getAbsolutePath().endsWith(Constant.POSTFIX_PDF_UPCASE)) {
			reslut = true;
		}
		return reslut;
	}
	/**
	 * @return the userPath
	 */
	public String getUserPath() {
		return userPath;
	}
	/**
	 * @param userPath the userPath to set
	 */
	public void setUserPath(String userPath) {
		this.userPath = userPath;
	}
	/**
	 * @return the backPath
	 */
	public String getBackPath() {
		return backPath;
	}
	/**
	 * @param backPath the backPath to set
	 */
	public void setBackPath(String backPath) {
		this.backPath = backPath;
	}

}
